package com.zhoug.demo.viewpermission;

import android.text.TextUtils;

import com.zhoug.logging.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;

/**
 * @author: zhoug
 * @since: 2025-06-12
 */
public class Utils {
    private static final String TAG = ">>>Utils";

    /**
     * 构建树形结构
     * @param flatList 平铺的，没有树形结构的数据
     * @return 属性结果的集合
     * @param <T>
     */
    public static <T> List<T> buildTree(List<T> flatList,@NonNull TreeProvider<T> provider){
        if (flatList == null || flatList.isEmpty()) return null;
        //1. 创建哈希表：id -> T 节点
        Map<String, T> nodeMap = new HashMap<>();
        for (T item : flatList) {
            nodeMap.put(provider.getId(item), item);
        }
        //创建属性结构
        List<T> treeList = new ArrayList<>();
        for (T item : flatList) {
            String parentId = provider.getParentId(item);
            //根节点
            if (TextUtils.isEmpty(parentId)) {
                treeList.add(item);
//                treeList.add(nodeMap.get(provider.getId(item)));
            } else {
                T parent = nodeMap.get(parentId);
                if (parent != null) {
                    List<T> children = provider.getChildren(parent);
                    if (children == null) {
                        children = new ArrayList<>();
                        provider.setChildren(parent,children);
                    }
//                    children.add(nodeMap.get(provider.getId(item)));
                    children.add(item);
                }

            }
        }
        return treeList;
    }

    /**
     * 递归打印节点
     * @param treeList 树状结构数据
     * @param depth 每层节点递增1
     * @param provider
     * @param <T>
     */
    public static <T> void printTree(List<T> treeList, int depth, @NonNull PrintTreeProvider<T> provider) {
        final String tag=">>>printTree";
        if(treeList==null){
            Logger.d(tag, "null");
            return;
        }
        if(treeList.isEmpty()){
            Logger.d(tag, "[]");
            return;
        }
        for (T item : treeList) {
            String indent = "  ".repeat(depth);
            Logger.d(tag, indent+provider.getPrintString(item));
            List<T> children = provider.getChildren(item);
            if(children!=null && !children.isEmpty()){
                printTree(children,depth+1,provider);
            }
        }
    }
}
